<template>
    <main class="main-page" id="">
        <section class="page-section mb-3">
            <div class="container-fluid">
                <div class="grid justify-content-between align-items-center">
                    <div class="col">
                        <div class="flex align-items-center gap-2">
                            <i class="pi pi-desktop text-primary text-2xl"></i>
                            <div class="text-2xl text-primary font-bold">
                                系统监控 - 性能分析
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <section class="page-section">
            <div class="container-fluid">
                <div class="grid">
                    <div class="col-12" v-if="showAlerts">
                        <Card class="mb-3">
                            <template #title>
                                <div class="flex align-items-center gap-2">
                                    <i class="pi pi-exclamation-triangle text-red-500"></i>
                                    <span>告警通知</span>
                                </div>
                            </template>
                            <template #content>
                                <div class="grid">
                                    <div class="col-12" v-if="cpuAlertActive">
                                        <div class="flex align-items-center gap-2 p-3 bg-red-50 border-round">
                                            <i class="pi pi-desktop text-red-500 text-xl"></i>
                                            <span class="text-red-700">CPU使用率 {{ currentCpuUsage }}% 超过警告阈值 {{ cpuThreshold }}%</span>
                                            <Button icon="pi pi-times" @click="dismissCpuAlert" class="p-button-text p-button-rounded p-button-danger ml-auto" />
                                        </div>
                                    </div>
                                    <div class="col-12" v-if="memoryAlertActive">
                                        <div class="flex align-items-center gap-2 p-3 bg-orange-50 border-round mt-2">
                                            <i class="pi pi-server text-orange-500 text-xl"></i>
                                            <span class="text-orange-700">内存使用率 {{ currentMemoryUsage }}% 超过警告阈值 {{ memoryThreshold }}%</span>
                                            <Button icon="pi pi-times" @click="dismissMemoryAlert" class="p-button-text p-button-rounded p-button-warning ml-auto" />
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </Card>
                    </div>

                    <div class="col-12">
                        <Card class="mb-3">
                            <template #title>
                                <div class="flex align-items-center gap-2">
                                    <i class="pi pi-info-circle text-primary"></i>
                                    <span>系统信息</span>
                                </div>
                            </template>
                            <template #content>
                                <div class="grid">
                                    <div class="col-12 md:col-6">
                                        <div class="flex flex-column gap-3">
                                            <div class="flex align-items-center gap-2">
                                                <i class="pi pi-desktop text-500"></i>
                                                <span class="font-bold">主机名：</span>
                                                <span>{{ systemInfo.hostname || '获取中...' }}</span>
                                            </div>
                                            <div class="flex align-items-center gap-2">
                                                <i class="pi pi-window-maximize text-500"></i>
                                                <span class="font-bold">操作系统：</span>
                                                <span>{{ systemInfo.os_type || '获取中...' }} {{ systemInfo.os_release || '' }}</span>
                                            </div>
                                            <div class="flex align-items-center gap-2">
                                                <i class="pi pi-th-large text-500"></i>
                                                <span class="font-bold">平台：</span>
                                                <span>{{ systemInfo.platform || '获取中...' }}</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-12 md:col-6">
                                        <div class="flex flex-column gap-3">
                                            <div class="flex align-items-center gap-2">
                                                <i class="pi pi-microchip text-500"></i>
                                                <span class="font-bold">CPU型号：</span>
                                                <span>{{ systemInfo.cpu_model || '获取中...' }}</span>
                                            </div>
                                            <div class="flex align-items-center gap-2">
                                                <i class="pi pi-cog text-500"></i>
                                                <span class="font-bold">CPU核心数：</span>
                                                <span>{{ systemInfo.cpu_count || '获取中...' }} 核</span>
                                            </div>
                                            <div class="flex align-items-center gap-2">
                                                <i class="pi pi-server text-500"></i>
                                                <span class="font-bold">总内存：</span>
                                                <span>{{ systemInfo.total_memory || '获取中...' }} GB</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </Card>
                    </div>

                    <div class="col-12">
                        <Card>
                            <template #title>
                                <div class="flex align-items-center gap-2">
                                    <i class="pi pi-chart-line text-primary"></i>
                                    <span>性能分析报告</span>
                                </div>
                            </template>
                            <template #content>
                                <div class="grid">
                                    <div class="col-12 md:col-6">
                                        <div class="flex flex-column gap-3">
                                            <h3 class="text-xl font-bold">实时监控</h3>
                                            <div class="card">
                                                <Chart type="line" :data="chartData" :options="chartOptions" height="300px" />
                                            </div>
                                            <div class="mt-3">
                                                <Button icon="pi pi-cog" label="告警设置" @click="showSettings = !showSettings" class="p-button-outlined p-button-secondary" />
                                                <div v-if="showSettings" class="mt-3 p-3 border-1 border-gray-200 border-round">
                                                    <h4 class="text-lg font-bold mb-3">警报阈值设置</h4>
                                                    <div class="grid">
                                                        <div class="col-6">
                                                            <div class="field">
                                                                <label class="block mb-2">CPU阈值 (%)</label>
                                                                <InputNumber v-model="cpuThreshold" inputId="cpuThreshold" :min="50" :max="95" class="w-full" />
                                                            </div>
                                                        </div>
                                                        <div class="col-6">
                                                            <div class="field">
                                                                <label class="block mb-2">内存阈值 (%)</label>
                                                                <InputNumber v-model="memoryThreshold" inputId="memoryThreshold" :min="50" :max="95" class="w-full" />
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-12 md:col-6">
                                        <div class="flex flex-column gap-3">
                                            <h3 class="text-xl font-bold">当前状态</h3>
                                            <div class="grid">
                                                <div class="col-12 mb-4">
                                                    <div class="card">
                                                        <h4 class="text-lg font-bold mb-2">CPU使用率: {{ currentCpuUsage }}%</h4>
                                                        <ProgressBar :value="currentCpuUsage" :class="getCpuProgressBarClass()" />
                                                        <div class="flex justify-content-between mt-2 text-sm">
                                                            <span class="text-500">负载: {{ systemInfo.loadavg ? systemInfo.loadavg[0].toFixed(2) : '0.00' }}</span>
                                                            <span class="text-500">空闲: {{ 100 - currentCpuUsage }}%</span>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="col-12">
                                                    <div class="card">
                                                        <h4 class="text-lg font-bold mb-2">内存使用率: {{ currentMemoryUsage }}%</h4>
                                                        <ProgressBar :value="currentMemoryUsage" :class="getMemoryProgressBarClass()" />
                                                        <div class="flex justify-content-between mt-2 text-sm">
                                                            <span class="text-500">已用: {{ systemInfo.total_memory && systemInfo.free_memory ? (parseFloat(systemInfo.total_memory) - parseFloat(systemInfo.free_memory)).toFixed(2) : '0.00' }} GB</span>
                                                            <span class="text-500">空闲: {{ systemInfo.free_memory ? parseFloat(systemInfo.free_memory).toFixed(2) : '0.00' }} GB</span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="mt-4">
                                                <div class="card">
                                                    <h4 class="text-lg font-bold mb-2">系统运行时间: {{ uptime }} 分钟</h4>
                                                    <div class="text-sm text-500">
                                                        <span>状态更新时间: </span>
                                                        <span class="text-primary font-bold">{{ lastUpdateTime }}</span>
                                                        <span class="ml-2 text-xs text-blue-500">(已更新 {{ updateCounter }} 次)</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </Card>
                    </div>
                </div>
            </div>
        </section>

        <Toast position="top-right" />
    </main>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { useApp } from 'src/composables/app.js';
import Card from 'primevue/card';
import Tag from 'primevue/tag';
import Dialog from 'primevue/dialog';
import Chart from 'primevue/chart';
import Button from 'primevue/button';
import ProgressBar from 'primevue/progressbar';
import InputNumber from 'primevue/inputnumber';
import Toast from 'primevue/toast';
import { useToast } from 'primevue/usetoast';

const app = useApp();
const toast = useToast();
const showSettings = ref(false);
const lastUpdateTime = ref('--:--:--');
const API_BASE_URL = process.env.VUE_APP_API_PATH || 'http://localhost:8060/api/';

// 系统信息
const systemInfo = ref({
    hostname: '',
    os_type: '',
    os_release: '',
    platform: '',
    cpu_model: '',
    cpu_count: 0,
    total_memory: 0,
    free_memory: 0,
    loadavg: [0, 0, 0]
});

// 告警相关的状态管理
const cpuThreshold = ref(80);
const memoryThreshold = ref(75);
const cpuAlertActive = ref(false);
const memoryAlertActive = ref(false);
const showAlerts = computed(() => cpuAlertActive.value || memoryAlertActive.value);
const currentCpuUsage = ref(0);
const currentMemoryUsage = ref(0);
const uptime = ref(0);
const consecutiveHighCpuCount = ref(0);
const consecutiveHighMemoryCount = ref(0);

// 添加更新计数器
const updateCounter = ref(0);

// 图表数据
const chartData = ref({
    labels: [],
    datasets: [
        {
            label: 'CPU使用率',
            backgroundColor: 'rgba(66, 165, 245, 0.2)',
            borderColor: '#42A5F5',
            data: [],
            tension: 0.4,
            fill: true
        },
        {
            label: '内存使用率',
            backgroundColor: 'rgba(255, 167, 38, 0.2)',
            borderColor: '#FFA726',
            data: [],
            tension: 0.4,
            fill: true
        }
    ]
});

const chartOptions = ref({
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
        legend: {
            position: 'top'
        },
        tooltip: {
            mode: 'index',
            intersect: false
        }
    },
    scales: {
        y: {
            beginAtZero: true,
            max: 100,
            title: {
                display: true,
                text: '使用率 (%)'
            }
        },
        x: {
            title: {
                display: true,
                text: '时间'
            }
        }
    }
});

function getCpuProgressBarClass() {
    if (currentCpuUsage.value >= cpuThreshold.value) {
        return 'custom-progress-bar-danger';
    } else if (currentCpuUsage.value >= cpuThreshold.value * 0.8) {
        return 'custom-progress-bar-warning';
    }
    return 'custom-progress-bar-normal';
}

function getMemoryProgressBarClass() {
    if (currentMemoryUsage.value >= memoryThreshold.value) {
        return 'custom-progress-bar-danger';
    } else if (currentMemoryUsage.value >= memoryThreshold.value * 0.8) {
        return 'custom-progress-bar-warning';
    }
    return 'custom-progress-bar-normal';
}

// 关闭CPU告警
function dismissCpuAlert() {
    cpuAlertActive.value = false;
    consecutiveHighCpuCount.value = 0;
}

// 关闭内存告警
function dismissMemoryAlert() {
    memoryAlertActive.value = false;
    consecutiveHighMemoryCount.value = 0;
}

// 获取真实系统性能数据
async function fetchSystemPerformance() {
    try {
        // 增加更新计数
        updateCounter.value++;
        console.log(`[系统监控] 第 ${updateCounter.value} 次数据更新...`);
        
        // 从后端API获取数据
        const token = localStorage.getItem('token') || sessionStorage.getItem('token');
        
        // 定义请求配置，不再强制要求令牌
        const requestConfig = {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        };
        
        // 如果有令牌，添加到请求头中
        if (token) {
            requestConfig.headers['Authorization'] = `Bearer ${token}`;
        }
        
        const response = await fetch(`${API_BASE_URL}system-performance`, requestConfig);
        
        if (!response.ok) {
            console.error('获取系统性能数据失败:', response.status);
            await fallbackToMockData();
            return;
        }
        
        const data = await response.json();
        
        // 更新系统信息
        systemInfo.value = {
            hostname: data.hostname,
            os_type: data.os_type,
            os_release: data.os_release,
            platform: data.platform,
            cpu_model: data.cpu_model,
            cpu_count: data.cpu_count,
            total_memory: data.total_memory,
            free_memory: data.free_memory,
            loadavg: data.loadavg
        };
        
        // 更新当前性能数据
        currentCpuUsage.value = data.cpu_usage;
        currentMemoryUsage.value = data.memory_usage;
        uptime.value = data.uptime;
        lastUpdateTime.value = data.timestamp;
        
        // 安全地更新图表数据
        const newLabels = [...chartData.value.labels, data.timestamp];
        const newCpuData = [...chartData.value.datasets[0].data, data.cpu_usage];
        const newMemoryData = [...chartData.value.datasets[1].data, data.memory_usage];
        
        // 保持最多10个数据点
        if (newLabels.length > 10) {
            chartData.value = {
                labels: newLabels.slice(1),
                datasets: [
                    {
                        ...chartData.value.datasets[0],
                        data: newCpuData.slice(1)
                    },
                    {
                        ...chartData.value.datasets[1],
                        data: newMemoryData.slice(1)
                    }
                ]
            };
        } else {
            chartData.value = {
                labels: newLabels,
                datasets: [
                    {
                        ...chartData.value.datasets[0],
                        data: newCpuData
                    },
                    {
                        ...chartData.value.datasets[1],
                        data: newMemoryData
                    }
                ]
            };
        }
        
        // 检查CPU使用率告警条件
        checkCpuAlert();
        
        // 检查内存使用率告警条件
        checkMemoryAlert();
        
    } catch (error) {
        console.error('处理系统性能数据出错:', error);
        await fallbackToMockData();
    }
}

// 在API请求失败时使用模拟数据
async function fallbackToMockData() {
    toast.add({
        severity: 'error',
        summary: '连接错误',
        detail: '无法连接到系统监控API，暂时使用模拟数据',
        life: 5000
    });
    
    // 生成当前时间
    const now = new Date();
    const timestamp = now.toLocaleTimeString();
    lastUpdateTime.value = timestamp + ' (模拟)';
    
    // 生成模拟数据
    if (chartData.value.datasets[0].data.length === 0) {
        // 首次加载，设置初始值
        currentCpuUsage.value = 45;
        currentMemoryUsage.value = 60;
    } else {
        // 随机波动
        const prevCpuUsage = chartData.value.datasets[0].data[chartData.value.datasets[0].data.length - 1];
        const prevMemoryUsage = chartData.value.datasets[1].data[chartData.value.datasets[1].data.length - 1];
        
        let cpuChange = Math.random() * 10 - 5;
        let memoryChange = Math.random() * 6 - 3;
        
        currentCpuUsage.value = Math.max(5, Math.min(95, Math.round(prevCpuUsage + cpuChange)));
        currentMemoryUsage.value = Math.max(10, Math.min(90, Math.round(prevMemoryUsage + memoryChange)));
    }
    
    uptime.value += 1;
    
    // 更新图表
    const newLabels = [...chartData.value.labels, timestamp];
    const newCpuData = [...chartData.value.datasets[0].data, currentCpuUsage.value];
    const newMemoryData = [...chartData.value.datasets[1].data, currentMemoryUsage.value];
    
    if (newLabels.length > 10) {
        chartData.value = {
            labels: newLabels.slice(1),
            datasets: [
                {
                    ...chartData.value.datasets[0],
                    data: newCpuData.slice(1)
                },
                {
                    ...chartData.value.datasets[1],
                    data: newMemoryData.slice(1)
                }
            ]
        };
    } else {
        chartData.value = {
            labels: newLabels,
            datasets: [
                {
                    ...chartData.value.datasets[0],
                    data: newCpuData
                },
                {
                    ...chartData.value.datasets[1],
                    data: newMemoryData
                }
            ]
        };
    }
    
    // 检查CPU和内存告警
    checkCpuAlert();
    checkMemoryAlert();
}

function checkCpuAlert() {
    if (currentCpuUsage.value >= cpuThreshold.value) {
        consecutiveHighCpuCount.value++;
        if (consecutiveHighCpuCount.value >= 3 && !cpuAlertActive.value) {
            cpuAlertActive.value = true;
            toast.add({
                severity: 'error',
                summary: 'CPU告警',
                detail: `CPU使用率持续超过${cpuThreshold.value}%，当前值: ${currentCpuUsage.value}%`,
                life: 5000
            });
        }
    } else {
        consecutiveHighCpuCount.value = 0;
    }
}

function checkMemoryAlert() {
    if (currentMemoryUsage.value >= memoryThreshold.value) {
        consecutiveHighMemoryCount.value++;
        if (consecutiveHighMemoryCount.value >= 3 && !memoryAlertActive.value) {
            memoryAlertActive.value = true;
            toast.add({
                severity: 'warn',
                summary: '内存告警',
                detail: `内存使用率持续超过${memoryThreshold.value}%，当前值: ${currentMemoryUsage.value}%`,
                life: 5000
            });
        }
    } else {
        consecutiveHighMemoryCount.value = 0;
    }
}

let performanceTimer = null;

onMounted(() => {
    const pageTitle = "系统监控 - 性能分析";
    app.setPageTitle(pageTitle);
    
    // 首次加载数据
    fetchSystemPerformance();
    
    // 每3秒更新一次数据
    performanceTimer = setInterval(fetchSystemPerformance, 3000);
});

onUnmounted(() => {
    if (performanceTimer) {
        clearInterval(performanceTimer);
    }
});
</script>

<style scoped>
.main-page {
    padding: 1rem;
}

.custom-progress-bar-normal :deep(.p-progressbar-value) {
    background: #22c55e;
}

.custom-progress-bar-warning :deep(.p-progressbar-value) {
    background: #f59e0b;
}

.custom-progress-bar-danger :deep(.p-progressbar-value) {
    background: #ef4444;
}

.text-xs {
    font-size: 0.75rem;
}

.text-sm {
    font-size: 0.875rem;
}

.card {
    background: var(--surface-card);
    padding: 1rem;
    border-radius: var(--border-radius);
    box-shadow: 0 2px 1px -1px rgba(0,0,0,.2), 0 1px 1px 0 rgba(0,0,0,.14), 0 1px 3px 0 rgba(0,0,0,.12);
}

.field {
    margin-bottom: 1rem;
}
</style> 